<template>
  <div class="container" ref="container">
    <a-modal v-model:visible="visible" @ok="handleOk" centered :getContainer="() => container">
      <!-- 时长设置---timeSet -->
      <div class="time-set" v-if="modalType === 'timeSet'">
        <!-- 顶部标题 -->
        <div class="title">
          时长设置
          <!-- {{ getItemEndTime }} -->
          <a-tooltip>
            <template #title>决定视频组以哪个元素的时长为准</template>
            <info-circle-outlined style="margin-left: 5px; color: #737a87" />
          </a-tooltip>
        </div>
        <div class="desc">
          <a-radio-group v-model:value="time_strategy.type">
            <!-- 随音频，视频智能截取 -->
            <a-radio :value="2" style="display: flex; align-items: center; margin-top: 10px"
              :disabled="notVoice.disabled">
              <div style="
                  margin-left: 5px;
                  display: flex;
                  align-items: center;
                  font-weight: 500;
                " :class="{ active: time_strategy.type === 2 }">
                随音频，视频智能截取
                <span class="recommend">推荐</span>
                <span class="disabled" v-show="notVoice.disabled">{{
                  notVoice.msg
                }}</span>
              </div>
              <div style="margin-top: 5px; margin-left: 5px; color: #737a87">
                镜头时长=音频时长，视频随音频自动截取(内置去重策略)
              </div>
            </a-radio>

            <!-- 固定时长，智能去重 -->
            <a-radio :value="3" style="display: flex; align-items: center; margin-top: 10px">
              <div style="
                  margin-left: 5px;
                  display: flex;
                  align-items: center;
                  font-weight: 500;
                " :class="{ active: time_strategy.type === 3 }">
                固定时长，智能去重
                <span class="recommend">推荐</span>
              </div>
              <div style="margin-top: 5px; margin-left: 5px; color: #737a87">
                镜头时长=固定时长，自动对视频/音频进行截取(内置去重策略)
              </div>
              <div style="margin-top: 5px; margin-left: 5px; width: 120px" v-if="time_strategy.type === 3">
                <a-input-number v-model:value="time_strategy.fixed_time" addon-after="秒" id="inputNumber" size="small"
                  :min="2" :max="60" />
              </div>
            </a-radio>
            <!-- 视频原始时长 -->
            <a-radio :value="0" style="display: flex; align-items: center; margin-top: 10px">
              <div style="
                  margin-left: 5px;
                  display: flex;
                  align-items: center;
                  font-weight: 500;
                " :class="{ active: time_strategy.type === 0 }">
                视频原始时长
              </div>
              <div style="margin-top: 5px; margin-left: 5px; color: #737a87">
                保留视频的原始时长，不做改变
              </div>
            </a-radio>
            <!-- 视频原始时长-视频随音频自动变速 -->
            <a-radio :value="1" style="display: flex; align-items: center; margin-top: 10px"
              :disabled="notVoice.disabled">
              <div style="
                  margin-left: 5px;
                  display: flex;
                  align-items: center;
                  font-weight: 500;
                " :class="{ active: time_strategy.type === 1 }">
                音频原始时长
                <span class="disabled" v-show="notVoice.disabled">{{
                  notVoice.msg
                }}</span>
              </div>
              <div style="margin-top: 5px; margin-left: 5px; color: #737a87">
                以音频的时长为准，视频随音频自动变速
              </div>
            </a-radio>
          </a-radio-group>
        </div>
      </div>
      <!-- 混剪模式设置-----mixedShearMode -->
      <div class="mixed-shear-mode" v-if="modalType === 'mixedShearMode'">
        <!-- 顶部标题 -->
        <div class="title">
          混剪模式
          <a-tooltip>
            <template #title>决定视频组内素材与视频组合的方式</template>
            <info-circle-outlined style="margin-left: 5px; color: #737a87" />
          </a-tooltip>
        </div>
        <div class="desc">
          <a-radio-group v-model:value="type">
            <a-radio :value="2" style="display: flex; align-items: center; margin-top: 10px">
              <div style="margin-left: 5px; display: flex; align-items: center" :class="{ active: type === 2 }">
                智能混剪
              </div>
              <div style="margin-top: 5px; margin-left: 5px">
                当前镜头组的素材将切片后,随机参与视频组合
              </div>
            </a-radio>
            <a-radio :value="0" style="display: flex; align-items: center; margin-top: 10px">
              <div style="margin-left: 5px; display: flex; align-items: center" :class="{ active: type === 0 }">
                单视频混剪
              </div>
              <div style="margin-top: 5px; margin-left: 5px">
                当前镜头组，只挑选一个素材参与视频组合
              </div>
            </a-radio>
          </a-radio-group>
        </div>
      </div>
      <template #footer>
        <a-button key="back" @click="handleCancel">取消</a-button>
        <a-button key="submit" type="primary" @click="configAllhandle">配置到所有镜头组</a-button>
        <a-button key="submit" type="primary" @click="configHandleOk">配置本镜头组</a-button>
      </template>
    </a-modal>
  </div>
</template>

<script>
import { reactive, toRefs, computed, ref } from "vue";
import { InfoCircleOutlined } from "@ant-design/icons-vue";
import {
  DURATION_SETTING_CUT_VIDEO_BY_AUDIO,
  DURATION_SETTING_CUT_VIDEO_BY_FIEXD,
  DURATION_SETTING_CHANGE_VIDEO_BY_AUDIO,
  DURATION_SETTING_BY_VIDEO,
} from "../../../../../common/constants/shotstack";

import { hasVideo, hasText } from '@/common/utils/richTextProcessing.js'

// 仓库
import { useStore } from "vuex";
export default {
  components: {
    InfoCircleOutlined,
  },
  props: {
    // 父组件当前操作的镜头组
    targetIndex: {
      type: Number,
    },
  },
  setup(props, { emit }) {
    const state = reactive({
      visible: false, //控制弹窗显示隐藏
      modalType: "", //打开弹窗类型（timeSet:时长设置，mixedShearMode：混剪模式设置设置）
      type: 2, // 混剪模式 （0-单镜头混剪【当前镜头组，只挑选一个素材参与视频组合】，2-智能混剪 【当前镜头组的素材将切片后，随机参与视频组合】）
      time_strategy: {
        // 时长类型设置：（0-视频原始时长，1-随音频，视频自动变速 ，2-随音频，视频智能截取 ，3-固定时长，智能去重）
        type: 3,
        fixed_time: 0, //类型为 3-固定时长，智能去重 时有效
      },
    });
    // 仓库
    const store = useStore();
    // 仓库中的混剪数据
    const VideoMashup = computed({
      get() {
        return store.state.videoMixCut.VideoMashup;
      },
      set(val) {
        store.state.videoMixCut.VideoMashup = val;
        store.dispatch("videoMixCut/SetVideoMashup", VideoMashup.value);
      },
    });

    // 更新仓库中的数据
    const updateStore = (data) => {
      store.commit("videoMixCut/SET_VIDEOMASHUP_ITEM", {
        key: "resource_data",
        value: data.value,
      });
    };
    // 获取当前视频组内的文本情况 空:false 有值:true
    const isNotEmpty = computed(() => {
      let targetData = VideoMashup.value.resource_data[props.targetIndex];

      return hasText({
        targetData
      })
      let isNotEmpty = false;
      // 当前编辑的项
      // let targetData = VideoMashup.value.resource_data[props.targetIndex];
      if (targetData.tab_id == "text") {
        const text_tts_config = targetData.tts_config.filter(
          (ele) => ele.tab_id == "text"
        );
        isNotEmpty = text_tts_config.some((ele) => {
          return ele.subtitle.some(
            (i) => !!i.text.trim() && i.text.trim() !== "\n"
          );
        });
      } else if (targetData.tab_id == "audio") {
        const audio_tts_config = targetData.tts_config.filter(
          (ele) => ele.tab_id == "audio"
        );
        isNotEmpty = audio_tts_config.some((ele) => {
          return ele.subtitle.some(
            (i) => !!i.text.trim() && i.text.trim() !== "\n"
          );
        });
      }
      return isNotEmpty;
    });

    // 检测是每一项都有音频字段
    // const haveAudio = computed(() => {
    //   let targetData = VideoMashup.value.resource_data[props.targetIndex]
    //   if (targetData.tab_id == 'text') {
    //     const targets = targetData.tts_config.filter(ele => ele.tab_id == 'text')
    //     const have = targets.some(ele => ele.subtitle.some(i => !i.audio_url))
    //     return have
    //   } else if (targetData.tab_id == 'audio') {
    //     const targets = targetData.tts_config.filter(ele => ele.tab_id == 'audio')
    //     return targets.every(ele => ele.audio_url)
    //   }
    // })

    // 是否禁用随音频，视频智能截取, 有文本且开启音频才不禁用
    const notVoice = computed({
      get() {
        let targetData = VideoMashup.value.resource_data[props.targetIndex];

        return hasVideo({
          targetData,
          VideoMashup,
          isNotEmpty
        })

      },
    });

    // 获取配置到本视频组的结束时间
    const getItemEndTime = computed(() => {
      let targetData = VideoMashup.value.resource_data[props.targetIndex];
      let activeItem = null;
      if (targetData.tab_id == "text") {
        activeItem = targetData.tts_config.filter(
          (ele) => ele.tab_id == "text"
        )[0];
        const time = activeItem.duration
        // const time = activeItem.subtitle
        //   .map((ele) => ele.duration)
        //   .reduce((total, item) => {
        //     return (total += +item);
        //   }, 0);
        console.log(
          time.toFixed(0),
          "time.toFixed(0)time.toFixed(0)time.toFixed(0)time.toFixed(0)time.toFixed(0)"
        );
        return +time.toFixed(0);
      } else if (targetData.tab_id == "audio") {
        activeItem = targetData.tts_config.filter(
          (ele) => ele.tab_id == "audio"
        )[0];

        return +(activeItem.duration !== ""
          ? activeItem.duration.toFixed(0)
          : 0);
      }
    });

    const showModal = (type) => {
      // debugger
      state.time_strategy = JSON.parse(
        JSON.stringify(
          VideoMashup.value.resource_data[props.targetIndex].time_strategy
        )
      );
      state.time_strategy.fixed_time = state.time_strategy.fixed_time / 1000;
      state.type = VideoMashup.value.resource_data[props.targetIndex].type;
      state.modalType = type;
      state.visible = true;
    };

    const handleCancel = () => {
      state.visible = false;
    };
    // 配置到所有镜头组
    const configAllhandle = () => {
      // 时长设置
      if (state.modalType == "timeSet") {
        // 设置固定时长
        if (state.time_strategy.type === DURATION_SETTING_CUT_VIDEO_BY_FIEXD) {
          // 判断时长至少2秒
          if (state.time_strategy.fixed_time < 2) {
            state.time_strategy.fixed_time = 2;
          }
          VideoMashup.value.resource_data.forEach((ele) => {
            ele.time_strategy = JSON.parse(JSON.stringify(state.time_strategy));
            ele.time_strategy.fixed_time *= 1000;
            // 修改所有配置项的end_time
            ele.material_list.forEach((item) => {
              // 图片生效
              // debugger
              console.log(
                state.time_strategy.fixed_time * 1000,
                "----",
                item.end_time
              );
              if (item.scene_type == "image") {
                item.end_time = state.time_strategy.fixed_time * 1000;
                // item.material_duration = state.time_strategy.fixed_time * 1000;
              } else {
                // 视频时间没超过最大时长 则使用配置的最大时长
                if (
                  !(
                    state.time_strategy.fixed_time * 1000 >
                    item.material_duration
                  )
                ) {
                  item.end_time = state.time_strategy.fixed_time * 1000;
                } else {
                  item.end_time = item.material_duration;
                }
              }
            });
          });
        } else if (
          state.time_strategy.type == DURATION_SETTING_CUT_VIDEO_BY_AUDIO ||
          state.time_strategy.type == DURATION_SETTING_CHANGE_VIDEO_BY_AUDIO
        ) {
          // debugger
          // 随音频智能截取和随音频自动变速 => 只有有文本并且开启音频, 并且有音频才生效
          VideoMashup.value.resource_data.forEach((ele) => {
            if (ele.tab_id == "text") {
              const text_tts_configs = ele.tts_config.filter(
                (item) => item.tab_id == "text"
              );
              const isNotEmptyAndShowVoice = text_tts_configs.some((item) => {
                return (
                  item.subtitle.some(
                    (i) => !!i.text.trim() && i.text.trim() !== "\n"
                  ) && item.showVoice
                );
              });
              // 是否有一项没有音频, 如果是的话, 那么此项不能设置为随音频
              const haveVideo = text_tts_configs.some((ele) =>
                ele.subtitle.some((i) => !i.audio_url)
              );
              console.log(
                isNotEmptyAndShowVoice || !haveVideo,
                "isNotEmptyAndShowVoice || !haveVideo"
              );
              if (isNotEmptyAndShowVoice || !haveVideo) {
                const allTextTime = text_tts_configs.reduce((totalDuration, item) => {
              // 计算当前 item 中 subtitle 所有 duration 的总和
              const currentItemDuration = item.subtitle.reduce((prev, next) => prev + +next.duration, 0);
              // 将当前 item 的总 duration 累加到总时长中
              return totalDuration + currentItemDuration;
          }, 0);
                console.log(allTextTime,'allTextTime是啥??????');
                
                // const allTextTime = text_tts_configs[0].duration
                // 修改所有配置项的end_time
                // const end_time = allTextTime[0].toFixed(0);
                const end_time = allTextTime.toFixed(0);
                console.log(end_time, "end_timeend_timeend_timeend_time");
                if (
                  state.time_strategy.type ==
                  DURATION_SETTING_CUT_VIDEO_BY_AUDIO
                ) {
                  // 如果是智能截取 =>
                  ele.material_list.forEach((item) => {
                    if (item.scene_type == "image") {
                      item.end_time = +end_time;
                    } else {
                      if (end_time <= item.material_duration) {
                        item.end_time = +end_time;
                      } else {
                        item.end_time = +item.material_duration;
                      }
                    }
                  });
                } else if (
                  state.time_strategy.type ==
                  DURATION_SETTING_CHANGE_VIDEO_BY_AUDIO
                ) {
                  // 如果是随音频自动变速 => 变速允许音频时长超出素材时长
                  ele.material_list.forEach((item) => {
                    item.end_time = +end_time;
                  });
                }
                // 修改所有符合条件的配置项的time_strategy
                ele.time_strategy = JSON.parse(
                  JSON.stringify(state.time_strategy)
                );
                ele.time_strategy.fixed_time *= 1000;
              }
            } else if (ele.tab_id == "audio") {
              const text_tts_configs = ele.tts_config.filter(
                (ele) => ele.tab_id == "audio"
              );
              const isNotEmptyAndShowVoice = text_tts_configs.some((ele) => {
                return ele.audio_url != "";
              });
              // 如果选择的是音频, 且有配音数据
              if (isNotEmptyAndShowVoice) {
                // 获取第一条音频的时长
                const end_time = (
                  text_tts_configs[0].end_time - text_tts_configs[0].start_time
                ).toFixed(0);
                ele.material_list.forEach((item) => {
                  if (
                    state.time_strategy.type ==
                    DURATION_SETTING_CUT_VIDEO_BY_AUDIO
                  ) {
                    // 如果是智能截取 =>
                    if (item.scene_type == "image") {
                      item.end_time = end_time;
                    } else {
                      if (end_time <= item.material_duration) {
                        item.end_time = +end_time;
                      } else {
                        item.end_time = +item.material_duration;
                      }
                    }
                  } else {
                    // 如果是随音频自动变速 =>
                    item.end_time = end_time;
                  }
                });

                // 修改所有符合条件的配置项的time_strategy
                ele.time_strategy = JSON.parse(
                  JSON.stringify(state.time_strategy)
                );
                ele.time_strategy.fixed_time *= 1000;
              }
            }
          });
        } else if (state.time_strategy.type == DURATION_SETTING_BY_VIDEO) {
          // 原始时长
          VideoMashup.value.resource_data.forEach((ele) => {
            ele.material_list.forEach((i) => {
              i.end_time = i.material_duration;
            });
            // 修改所有符合条件的配置项的time_strategy
            ele.time_strategy = JSON.parse(JSON.stringify(state.time_strategy));
            ele.time_strategy.fixed_time *= 1000;
          });
        }
        updateStore({
          key: "resource_data",
          value: VideoMashup.value.resource_data,
        });

        setTimeout(() => {
          console.log(
            VideoMashup.value.resource_data,
            "更新仓库---设置视频时长，配置到全部镜头组"
          );
        }, 500);
      } else {
        // 混剪模式设置
        VideoMashup.value.resource_data = VideoMashup.value.resource_data?.map(
          (item) => {
            return {
              ...item,
              type: JSON.parse(JSON.stringify(state.type)),
            };
          }
        );
        // updateStore();
        setTimeout(() => {
          console.log(
            VideoMashup.value.resource_data,
            "更新仓库---设置混剪模式，配置到全部镜头组"
          );
        }, 500);
      }
      state.visible = false;
    };
    // 配置到本镜头组
    const configHandleOk = () => {
      // 时长设置
      if (state.modalType === "timeSet") {
        // 固定时间设置
        if (state.time_strategy.type == DURATION_SETTING_CUT_VIDEO_BY_FIEXD) {
          // 判断时长至少2秒
          if (state.time_strategy.fixed_time < 2) {
            state.time_strategy.fixed_time = 2;
          }
          VideoMashup.value.resource_data[props.targetIndex].time_strategy =
            JSON.parse(JSON.stringify(state.time_strategy));
          VideoMashup.value.resource_data[
            props.targetIndex
          ].time_strategy.fixed_time *= 1000;

          VideoMashup.value.resource_data[
            props.targetIndex
          ].material_list.forEach((item) => {
            // debugger
            // 图片生效
            if (item.scene_type == "image") {
              item.end_time = state.time_strategy.fixed_time * 1000;
            } else {
              console.log(
                state.time_strategy.fixed_time * 1000,
                "----",
                item.end_time
              );
              // 视频时间没超过最大时长 则使用配置的最大时长
              if (
                !(
                  state.time_strategy.fixed_time * 1000 >
                  item.material_duration
                )
              ) {
                item.end_time = state.time_strategy.fixed_time * 1000;
              } else {
                item.end_time = item.material_duration;
              }
            }
          });
        } else if (
          state.time_strategy.type == 2 ||
          state.time_strategy.type == 1
        ) {
          // TODO 随音频需要有文本且开启音频设置 配置本镜头需要修改素材时长
          VideoMashup.value.resource_data[
            props.targetIndex
          ].material_list.forEach((item) => {
            // 随音频自动变速
            if (state.time_strategy.type == 1) {
              item.end_time = getItemEndTime.value;
            } else {
              // 智能截取
              if (item.scene_type == "image") {
                item.end_time = getItemEndTime.value;
              } else {
                // 视频时间没超过最大时长 则使用配置的最大时长
                if (!(getItemEndTime.value > item.material_duration)) {
                  item.end_time = getItemEndTime.value;
                } else {
                  item.end_time = item.material_duration;
                }
              }
            }
          });
          VideoMashup.value.resource_data[props.targetIndex].time_strategy =
            JSON.parse(JSON.stringify(state.time_strategy));
          VideoMashup.value.resource_data[
            props.targetIndex
          ].time_strategy.fixed_time *= 1000;
        } else {
          // 视频原始时长
          VideoMashup.value.resource_data[
            props.targetIndex
          ].material_list.forEach((item) => {
            item.end_time = item.material_duration;
          });
          VideoMashup.value.resource_data[props.targetIndex].time_strategy =
            JSON.parse(JSON.stringify(state.time_strategy));
          VideoMashup.value.resource_data[
            props.targetIndex
          ].time_strategy.fixed_time *= 1000;
        }
        updateStore({
          key: "resource_data",
          value: VideoMashup.value.resource_data,
        });
        setTimeout(() => {
          console.log(
            VideoMashup.value.resource_data,
            "更新仓库---设置视频时长配置到本镜头组"
          );
        }, 500);
      } else {
        // 混剪模式设置
        VideoMashup.value.resource_data[props.targetIndex].type = state.type;
        // updateStore();
        setTimeout(() => {
          console.log(
            VideoMashup.value.resource_data,
            "更新仓库---设置混剪模式配置到本镜头组"
          );
        }, 500);
      }
      state.visible = false;
    };

    const container = ref()
    return {
      ...toRefs(state),
      showModal,
      container,
      handleCancel,
      configAllhandle,
      configHandleOk,
      isNotEmpty,
      VideoMashup,
      notVoice,
      getItemEndTime,
    };
  },
};
</script>

<style lang="less" scoped>

// 去除边框线
:deep(.ss-modal-header) {
  border-bottom: none !important;
}

:deep(.ss-modal-footer) {
  border-top: none !important;
  padding: 10px 16px 22px 16px;
}


.container{
  // 设置弹窗圆角
:deep(.ss-modal-content) {
  border-radius: 10px;
  overflow: hidden;
}
}


.recommend {
  display: inline-block;
  border-radius: 8px;
  background: #2878ff;
  color: #fff;
  font-size: 10px;
  padding: 2px 8px;
  text-align: center;
  margin: 0 5px;
}

.disabled {
  background: #f1f3f5;
  font-size: 10px;
  border-radius: 6px;
  padding: 1px 5px;
  color: #737a87;
}

.desc {
  margin-top: 10px;
}

.active {
  color: #2878ff;
}
</style>
